<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 10:15
 */
namespace app\admin\controller;

use app\admin\model\BusinessMobel;
use app\admin\model\MemberModel;
use app\admin\model\OrderModel;
use app\admin\model\RoleModel;
use app\admin\model\DepartmentModel;
use think\Db;

class Business extends Base{
    //调用当前用户下的部门 13 -21
    public function _initialize(){
        parent::_initialize();
        $uid = session('id');
        if (empty(session('can_see')[0])) {
            $department_id =Db::name('department')->where(['pid'=>0])->value('id');
        }else{
            $role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
            $department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
        }
        // $role_id = Db::name('user')->where(['id'=>$uid])->value('role_id');
        // $department_id =Db::name('role')->where(['id'=>$role_id])->value('department_id');
        $roleModel = new RoleModel();
        $departUserID = $roleModel->getUsersByDepartIdCansee($department_id);
        $where['id'] = array('in',$departUserID);
        //查询当前部门下的所有职员
        $departUserArr = Db::name('user')->field(['id','real_name'])->where($where)->select();
        $myArr = Db::name('department')->where('id',$department_id)->find();
        $dep_Arr = $this->DeparArr($department_id);
        $myArr['children'] = $dep_Arr;
        $departArr[0] = $myArr;
        $option = $this->arr2Tree($departArr);
        $this->assign([
            'dep_Arr'       => $option,
            'departUserArr' => $departUserArr,
            'id'            => $uid
        ]);
    }
    public function arr2Tree($arr,$option='',$strk = ''){
        $str = '| - ';
        foreach($arr as $v){
            $option .= '<option value="'.$v['id'].'">'.$str.$strk.$v['name'].'</option>';
            if(!empty($v['children'])){
                $strk .= '- - ';
                $option = $this->arr2Tree($v['children'],$option,$strk);
                $strk = mb_substr($strk,4,mb_strlen($strk));
            }
        }
        return $option;
    }

    public function DeparArr($id){
        $arr= [];
        $departArr = Db::name('department')->where('pid',$id)->select();
        foreach ($departArr as $key => $value){
            $value['children'] = $this->DeparArr($value['id']);
            $arr[] = $value;
        }
        return $arr;
    }
    //Ajax 获取选择部门的职员信息
    public function departUser(){
        $depart_id = input('post.depart_id');
        // $roleModel = new RoleModel();
        // $departUserID = $roleModel->getUsersByDepartIdCansee($depart_id);
        $finance = new Finance();
    		$departUserID = $finance->getAllRolesAndAllUsersByParentDepart($depart_id);
    		$where['id'] = array('in',$departUserID['userArr']);
        // $where['id'] = array('in',$departUserID);
        //查询当前部门下的所有职员
        $departUserArr = Db::name('user')->field(['id','real_name'])->where($where)->select();
        return json(['code'=>1,'data'=>$departUserArr]);
    }
    /**
     * 业务管理
     * 黄
     * 18-4-19
    */
    public function index ()
    {

    }
    //客户信息录入
    public function businAdd (){
        $uid = session('id');
        $date = time();
        $business = new BusinessMobel();
        if(request()->isPost()){
            $param = input('post.');
            $param['first_relation'] = $uid;
            $param['entry_time'] = $date;
            $param['create_uid'] = $uid;
            $param['source'] = 0;//客户来源
			      $param['status'] = 6;//客户状态,强制改为跟踪状态

            $flag = $business->getBusinAdd($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        //客户等级
        $gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
        //生源途径
        $source_origin = Db::name('member_attr')->where(['pid'=>32])->select();
        $this->assign([
            'gradeArr' => $gradeArr,
            // 'statusArr' => $statusArr,
            'source_origin' => $source_origin
        ]);
        return $this->fetch();
    }
    //我的跟踪
    public function trackMem ()
    {
        if (request()->isAjax()) {
			      $uid = session('id');
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['name'])) {
                $where['name'] = ['like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }
            if (!empty($param['grade'])) {
                $where['grade'] = $param['grade'];
            }
            $where['status'] = 6;//强制使用状态
      			$where['delete_status'] = array('neq',2);//不是伪删除
      			$where['create_uid'] = session('id');
            $member = new MemberModel();
            $selectResult = $member->getMemberByWhere($where, $offset, $limit);
            foreach($selectResult as $key => $vo){
                $vo['status'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
                $vo['grade'] = Db::name('member_attr')->where(['id'=>$vo['grade']])->value('name');
        				//判断时间
        				$start_time = strtotime(date('Ymd',time())." 000000");
                        $end_time = strtotime(date('Ymd',time())." 235959");
        				if( (strtotime($vo['time_K']) >= $start_time) && (strtotime($vo['time_K']) <= $end_time)){
        					$vo['time'] = '<span style="color:red;"><b>'.$vo['time'].'</b></span>';
        				}
        				if($vo['share'] == 1){
        					$vo['operate'] = showOperate($this->makeButton2($vo['id']));
        				}else{
        					$vo['operate'] = showOperate($this->makeButton1($vo['id']));
        				}
        				//添加追踪信息
        				$vo['trackInfo'] = Db::name('track_member')->where(['m_id'=>$vo['id']])->order('id desc')->value('content');
        				// print_r(Db::name('track_member')->getLastSql());
            }
            $return['total'] = $member->getAllMember($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
        }
        //跟踪方式
        $tackType = Db::name('member_attr')->where(['pid'=>25])->select();
    		//客户等级
    		$gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
    		//生源途径
    		$source_origin = Db::name('member_attr')->where(['pid'=>32])->select();
        $this->assign([
            'gradeArr' => $gradeArr,
			      'tackType' => $tackType
        ]);
        return $this->fetch();
    }
	/**
	 * 添加追踪客户信息
	 * samsara
	 */
	 public function addTrack(){
		 $param = input('post.');
		 $param['u_id'] = session('id');
		 $param['m_id'] = $param['mid'];
		 $param['type'] = $param['track_type'];
		 $param['time'] = time();
		 $memberModel = new MemberModel();
		 $flas = $memberModel->addTrack($param);
		 return json($flas);
	 }
	 /**
 	 * 添加资源库客源状态
 	 * samsara
	 * [2018-6-14]
 	 */
	 public function resStatus(){
		 $param = input('post.');
		 $id = $param['mid'];
		 if($param['resStatus'] == 41 || $param['resStatus'] == 42 || $param['resStatus'] == 43){
			 //删除客源
			 $delete = Db::name('member')->where('id',$id)->delete();
			 if($delete){
				 return json(['code'=>1,'msg'=>'更新成功']);
			 }else{
				 return json(['code'=>0,'msg'=>'更新失败']);
			 }
		 }elseif ($param['resStatus'] == 44 || $param['resStatus'] == 45 || $param['resStatus'] == 46 || $param['resStatus'] == 47) {
			 //添加状态
			 $addStatus = Db::name('member')->where('id',$id)->update(['res_status' => $param['resStatus']]);
			 if($addStatus === false){
				return json(['code'=>0,'msg'=>'更新失败']);
			 }else{
				return json(['code'=>1,'msg'=>'更新成功']);
			 }
		 }else{
			 //添加至跟踪
			 $editStatus = Db::name('member')->where('id',$id)->update(['res_status' => $param['resStatus'],'status' => 6]);
			 if($editStatus === false){
				return json(['code'=>0,'msg'=>'更新失败']);
			}else{
				return json(['code'=>1,'msg'=>'更新成功']);
			}
		 }
	 }
	/**
	 * 客户分享
	 * @ share
	 * 黄
	 */
	 public function shareArtic(){
		 if (request()->isAjax()) {
			 $param = input('post.');
			 $id = $param['m_id'];
       $isOrder = Db::name('order')->where(['m_id'=>$id,'status'=>4])->find();
       if(!empty($isOrder)){
          return msg(-1, '', '不能分享存在订单的客户');
       }
			 $member = new MemberModel();
			 $flag = $member->shareStatus($id);
			 return json($flag);
		 }
 	 }
	 /**
	  * 取消分享
	  * samsara
	  */
	 public function cancelShare(){
		 if (request()->isAjax()) {
			 $param = input('post.');
			 $id = $param['m_id'];
			 $member = new MemberModel();
			 $flag = $member->cancelShare($id);
			 return json($flag);
		 }
	 }
    //我的订单
	 public function myOrder ()
	 {
		 $uid = session('id');
		 if(request()->isAjax()){
			 $param = input('param.');
             $limit = $param['pageSize'];
             $offset = ($param['pageNumber'] - 1) * $limit;
             $where = [];
             //客户姓名
             if(!empty($param['stu_name'])){
                 $where['stu_name'] = array('like','%'.$param['stu_name'].'%');
             }
             //时间
             if(!empty($param['c_time'])){
                 $start_time = strtotime(explode(" - ",$param['c_time'])[0]);
                 $end_time = strtotime(explode(" - ",$param['c_time'])[1]);
                 $where['c_time'] = array('between',[$start_time,$end_time]);
             }
             $where['delete_status'] = array('neq',1);

             $order = new OrderModel();

             //所属咨询师(成交人员)
             if(!empty($param['depart_id']) || !empty($param['user_id'])){
                //depart_id user_id
                if (!empty($param['depart_id'])) {
                    // $roleModel = new RoleModel();
                    // $departUserID = $roleModel->getUsersByDepartIdCansee($param['depart_id']);
                    // $where['consultant'] = array('in',$departUserID);
                    $finance = new Finance();
            				$departUserID = $finance->getAllRolesAndAllUsersByParentDepart($param['depart_id']);
            				$where['consultant'] = array('in',$departUserID['userArr']);
                }
                if(!empty($param['user_id'])){
                    $where['consultant'] = array('in',$param['user_id']);
                }
             }else{
        				 $canSee = session('can_see');
        				 $canArr = [];
        				 foreach($canSee as $val){
          					if (empty($val)) {
          					 	$canArr = Db::name('user')->column('id');
          					}else{
          						array_push($canArr,$val['create_uid']);
          					}
        				 }
                 $where['consultant'] = array('in',$canArr);
             }
             // 除去创建中的订单 2018-7-23
             // $where['status'] = ['neq',4];
			       $orderArr = $order->getMyOrder($where, $offset, $limit);
             foreach ($orderArr as $key=>&$value){
                 $value['stu_name'] = '<a href="'.url('member/memberInfo',['m_id'=>$value['m_id']]).'">'.$value['stu_name'].'</a>';
                 $u_id = $value['m_id'];
                 $grade = $value['grade'];//层次
                 $payment_method  = $value['payment_method'];//缴费方式
                 $consultant = $value['consultant'];
        				 //支付方式
        				 $value['pay_typeN'] = Db::name('member_attr')->where(['id'=>$value['pay_type']])->value('name');
                 $mem_phone = Db::name('member')->where(['id'=>$u_id])->value('phone');//查询当前订单的客户信息
                 $gradeN = Db::name('product_attr')->where(['id'=>$grade])->value('name');//获取当前层次
                 $payment_methodN = Db::name('product_attr')->where(['id'=>$payment_method])->value('name');
                 $consultantN = Db::name('user')->where('id',$consultant)->value('real_name');
                 $value['acquisition_mode'] = Db::name('product_attr')->where(['id'=>$value['acquisition_mode']])->value('name');
                 $value['phone'] = $mem_phone;
                 $value['gradeN'] = $gradeN;
                 $value['payment_methodN'] = $payment_methodN;
                 $value['consultantN'] = $consultantN;
                 if($value['status'] == 4){
                    if($value['create_uid'] == session('id')){
                        $value['operate'] = showOperate($this->makeButton5($value['m_id']));
                    }
                 }else{
                    $value['operate'] = showOperate($this->makeButton3($value['id']));
                 }
                 $value['c_time'] = date('Y-m-d',$value['c_time']);
             }
             $return['rows'] = $orderArr;
             $return['total'] = $order->getAllOrder($where);  // 总数据
             $return['sum'] = 0;
             foreach($return['rows'] as $val){
                 //增加总金额
                 $return['sum'] += $val['total_amount'];
             }
             return json($return);
		 }
		 return $this->fetch();
	 }
    /**
     * 订单详细信息
     * $id 订单id
     */
    public function orderInfo ()
    {
        $id = input('id');
        $order = new OrderModel();
        $ordeInfo = $order->getOrderInfo($id);
        //层次
        $gradeN = Db::name('product_attr')->where('id',$ordeInfo['grade'])->value('name');
        //制度
        $systemN = Db::name('product_attr')->where('id',$ordeInfo['system'])->value('name');
        //教育模式
        $acquisition_modeN = Db::name('product_attr')->where('id',$ordeInfo['acquisition_mode'])->value('name');
        //缴费方式
        $payment_methodN = Db::name('product_attr')->where('id',$ordeInfo['payment_method'])->value('name');
        //支付方式
		$ordeInfo['pay_typeN'] = Db::name('member_attr')->where(['id'=>$ordeInfo['pay_type']])->value('name');
        //订单状态
        switch ($ordeInfo['status']){
            case 1:
                $ordeInfo['statusN'] = '进行中';
                break;
            case 2:
                $ordeInfo['statusN'] = '已完成';
                break;
            case 3:
                $ordeInfo['statusN'] = '退款';
                break;
            default:
                $ordeInfo['statusN'] = '其他';
        }
        //创建时间
        $ordeInfo['c_time'] = date('Y-m-d',$ordeInfo['c_time']);
        //所属咨询师
        $ordeInfo['consultantN'] = Db::name('user')->where('id',$ordeInfo['consultant'])->value('real_name');
        //创建人
        $ordeInfo['createN'] = Db::name('user')->where('id',$ordeInfo['create_uid'])->value('real_name');

        $ordeInfo['gradeN'] = $gradeN;
        $ordeInfo['systemN'] = $systemN;
        $ordeInfo['acquisition_modeN'] = $acquisition_modeN;
        $ordeInfo['payment_methodN'] = $payment_methodN;
        $this->assign([
            'ordeInfo' => $ordeInfo
        ]);
        return $this->fetch();
    }

    /**
     * 新增资源客户
     * 由主管和主任分配的资源客户
     * @status @first_relation @source
     */
    public function resouMember(){
        if (request()->isAjax()) {
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['name'])) {
                $where['name'] = ['like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['phone'])) {
                $where['phone'] = ['like', '%' . $param['phone'] . '%'];
            }
			if (!empty($param['res_status'])) {
                $where['res_status'] = $param['res_status'];
            }
            //时间
            if(!empty($param['time'])){
                $start_time = strtotime(explode(" - ",$param['time'])[0].'00:00:00');
                $end_time = strtotime(explode(" - ",$param['time'])[1].'24:59:59');
                $where['entry_time'] = array('between',[$start_time,$end_time]);
            }
            $where['delete_status'] = array('neq',2);
            $where['first_relation'] = session('id');//第一录入人
            $where['status'] = 9;   //状态(由分配来的客户状态只能为资源库客户)
            $where['grade'] = 0;    //等级(由分配来的客户等级无状态)
            $where['source'] = 1;    //来源(由分配来的客户来源都是客户资源客户)
            $where['create_uid'] = session('id'); //创建人
            $member = new MemberModel();

            $selectResult = $member->getMemberByWhere($where, $offset, $limit);
            foreach($selectResult as $key=>&$vo){
                $vo['statusN'] = Db::name('member_attr')->where(['id'=>$vo['status']])->value('name');
				$vo['entry_time'] = date('Y-m-d',$vo['entry_time']);
				$vo['first_relation'] = Db::name('user')->where(['id'=>$vo['first_relation']])->value('real_name');
                $vo['operate'] = showOperate($this->makeButton4($vo['id']));
				//添加资源库客户状态
				$vo['resStatus'] = Db::name('member_attr')->where(['id'=>$vo['res_status']])->value('name');
				// print_r(Db::name('track_member')->getLastSql());
            }
            $return['total'] = $member->getAllMember($where);  // 总数据
            $return['rows'] = $selectResult;
            return json($return);
        }
        //客户等级
        $gradeArr = Db::name('member_attr')->where(['pid'=>1])->select();
        //客户状态
        $statusArr = Db::name('member_attr')->where(['pid'=>5])->select();
		//资源库客源状态
        $resStatus = Db::name('member_attr')->where(['pid'=>40])->select();
        $this->assign([
            'gradeArr' => $gradeArr,
            'statusArr' => $statusArr,
			'resStatus' => $resStatus
        ]);
        return $this->fetch();
    }
    /**
     * 拼装操作按钮
     * @param $id 跟踪记录
     * @return array
     */
    private function makeButton1($id)
    {
        return [
            '跟踪记录' => [
                'auth' => 'business/trackmem',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste',
            ],
	        '资源分享' => [
	            'auth' => 'business/shareartic',
	            'href' => 'javascript:shareartic('.$id.')',
	            'btnStyle' => 'primary',
	            'icon' => 'fa fa-paste',
			]
        ];
    }
	private function makeButton4($id)
    {
        return [
            '跟踪记录' => [
                'auth' => 'business/trackmem',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste',
            ]
        ];
    }
    /**
     * 查看信息 $id
     */
    private function makeButton2($id)
    {
        return [
			'跟踪记录' => [
                'auth' => 'business/trackmem',
                'href' => url('member/memberedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste',
            ],
            '取消分享' => [
                'auth' => 'business/shareartic',
                'href' => 'javascript:cancelshare('.$id.')',
                'btnStyle' => 'danger',
                'icon' => 'fa fa-search',
            ]
        ];
    }
    /**
     *添加按钮 $id
     */
    private function makeButton3($id){
        return [
            '查看订单' => [
                'auth' => 'business/orderinfo',
                'href' => url('business/orderinfo', ['id' => $id]),
                'btnStyle' => 'danger',
                'icon' => 'fa fa-paste',
            ]
        ];
    }
    /**
     *添加按钮 $id
     */
    private function makeButton5($id){
        return [
            '修改信息' => [
                'auth' => 'member/memberedit',
                'href' => url('member/memberedit', ['id' => $id]).'#test=55',
                'btnStyle' => 'success',
                'icon' => 'fa fa-paste',
            ]
        ];
    }
}
